<template>
  <div class="wrap">
    <dialog-input-search v-if="currentFolderList.length > 0"
                         v-model.trim="searchParts"
                         :placeholder="$t('message.ConvertHIToHATool.search')"
                         @input="changeSearchParts"/>
    <div v-if="currentFolderList.length > 0" class="op-dialog-part op-scroll-container">
      <dialog-documents :document-list="currentFolderList"
                        :searchText="searchParts"
                        @docClicked="selectDoc"
                        @sendTotalHeight="handleTotalHeight"/>

    </div>
<!--    <div class="d-flex align-items-center">-->
<!--      <el-checkbox  v-model="isCreateNewFolder"-->
<!--                    @change="changeCreateNewFolder"-->
<!--                    :label="$t('message.ConvertHIToHATool.createNewFolder')"/>-->
<!--    </div>-->
	  <div class="d-flex align-items-center">
      <label class="el-form-item__label">{{ $t('message.ConvertHIToHATool.folderName') + ':'}}</label>
      <el-input v-model="folderName"
                type="string"
                @change="changeFolderName"/>
    </div>
    <div class="btn">
      <el-button type="primary"
                 :disabled="isInit"
                 @click="clickExport">
        {{ $t('message.ConvertHIToHATool.export') }}
      </el-button>
      <el-button @click="close">{{ $t('message.ConvertHIToHATool.close') }}</el-button>
    </div>
  </div>
</template>

<script>
import {convertHIToHACommand} from "../../../command/ConvertHIToHACommand";
import {
  DocumentType
} from "../../../../nodeApp/static/lib/crowncad-plugin-sdk-0.0.1";
import DialogInputSearch from "./DialogInputSearch.vue";
import DialogDocuments from "./DialogDocuments.vue";


export default {
  components: {
    "dialog-input-search": DialogInputSearch,
    "dialog-documents": DialogDocuments,
  },
  data() {
    return {
      rootCode: "0",
      editingDocument: null,
      editingDocumentName: "",
      editingDocumentFolderCode: "",
      originalAssemblyTree: [],
      newAssemblyTree: [],
      instanceNameToInstanceInfoList: [],
      newInstanceList: [],
      createdInstanceIdList: [],
      rootAssemblInfo: null,
      protoRefInfoList: [],
      folderName: this.$t('message.ConvertHIToHATool.defaultFolderName'),
      folderCode: "",
	    lastFolderName: '',
	    path: "",
      newProjectId: "",
      hasSameInstanceName: false,
      isInit: true,
      currentReNameInstance: null,
      isChildrenReName: false,

	    //文件夹选择
	    folderList: [],
      currentFolderList: [],
      searchParts: '',
      selectedDocList: [],

      //创建装配
      currentDocType: DocumentType.PART,
      currentAssemblyTemplates: [],
      currentPartTemplates: [],
      assemblyTemplateInfo: {
        templateId: '',
        templateName: '',
        templateType: '',
        orderNumber: '',
        defaultTemplate: '',
        attrManifestTemplateId: '',
      },
      partTemplateInfo: {
        templateId: '',
        templateName: '',
        templateType: '',
        orderNumber: '',
        defaultTemplate: '',
        attrManifestTemplateId: '',
      },
    }
  },

  mounted() {
    convertHIToHACommand.init(500, 300, 500, async () => {
      this.folderList = await convertHIToHACommand.getAllFoldersUnderCurrentProject();
      this.currentFolderList = this.folderList;
      // let height = this.checkFolderCodeIsRootCode();
      this.changePluginContainerHeight(-35);
      this.folderName = await convertHIToHACommand.getDefaultDocumentName(DocumentType.FOLDER);
      let instance = await convertHIToHACommand.getInstanceTree();
      if(instance) {
        // console.log(instance);
        this.originalAssemblyTree = instance;
        let instanceList = this.originalAssemblyTree;
        await this.traverseAssemblyTree(instanceList);
      }
      this.editingDocument = await convertHIToHACommand.getEditingDocument();
      if(this.editingDocument) {
        this.editingDocumentName = this.editingDocument.name;
        this.editingDocumentFolderCode = this.editingDocument.folderCode;
      }
      this.isInit = false;
    });
  },

  methods: {
    //改变文件夹名称
    async changeFolderName(value) {
      let params = {
        docName: value,
        docType: DocumentType.FOLDER,
        folderCode: this.editingDocumentFolderCode
      }
      //检查同名文件夹
      let res = await convertHIToHACommand.checkRepeatDocumentName(params);
      if(res) {
        let msg = this.$t('message.ConvertHIToHATool.reFolderName');
        convertHIToHACommand.eventBusAlertMsg(msg, 'error');
        this.isInit = true;
      } else {
        this.isInit = false;
      }
    },
    //遍历并解析装配树
    async traverseAssemblyTree(instanceList) {
      if (instanceList.length === 0 || !instanceList) {
        return;
      }
      for (let i = 0; i < instanceList.length; i++) {
        let instanceId = instanceList[i].id;
        let name = instanceList[i].name;
        let instanceName = instanceList[i].instanceName;

        //实例名处理
        let index = - 1;
        let index1 = instanceName.indexOf('GBN');
        if (index1 !== -1) {
          let tempInstanceName = instanceName;
          let index2 = tempInstanceName.indexOf('<');
          if (index2 !== -1) {
            tempInstanceName = tempInstanceName.substr(0, index2);
            instanceName = tempInstanceName;
          }
          //处理相同实例名内核后缀
          let currentUnderlineCount = this.countUnderlineChar(instanceName);
          for(let j = 0; j < this.instanceNameToInstanceInfoList.length; j++) {
            let tempInstanceName = this.instanceNameToInstanceInfoList[j].instanceName;
            let tempUnderlineCount = this.countUnderlineChar(tempInstanceName);
            if(tempUnderlineCount === currentUnderlineCount - 1) {
              let pos = instanceName.lastIndexOf('_');
              let currentInstanceName = instanceName.substr(0, pos);
              if(currentInstanceName === tempInstanceName) {
                instanceName = currentInstanceName;
                index = j;
              }
            }
          }
        } else {
          instanceName = name;
        }

        //获取实例关联obj3d
        let obj3dData = await convertHIToHACommand.getInstanceObj3dByInstanceId(instanceId);
        //获取实例关联proto
        let protoData = await convertHIToHACommand.getInstanceProtoRefByInstanceId(instanceId);

        if (obj3dData && protoData) {
          let matrixWorld = obj3dData.matrixWorld;
          let position = obj3dData.position;
          let parentId = obj3dData?.parentId ? obj3dData?.parentId : null;
          let parentName = obj3dData?.parentName ? obj3dData?.parentName : null;

          let protoRefId = protoData.protoRefId;
          let protoRefDocId = protoData.protoRefDocId;
          let protoRefVersionId = protoData.protoRefVersionId;
          let protoRefName = protoData.protoRefName;
          let protoRefType = protoData.protoRefType;
          // if (!(protoRefType === "part") || protoRefName === "") {
          //   await this.traverseAssemblyTree(instanceList[i].children);
          //   continue;
          // }
          let instanceInfo = {
            instance: {
              id: instanceId,
              name: instanceName,
              matrixWorld: matrixWorld,
              position: position,
              parentId: parentId,
              parentName: parentName
            },
            protoRefInfo: {
              protoRefId: protoRefId,
              protoRefDocId: protoRefDocId,
              protoRefVersionId: protoRefVersionId,
              protoRefName: protoRefName,
              protoRefType: protoRefType
            }
          };

          let sameFlag = false;

          //查找同名实例
	        if(index === -1) {
            index = this.instanceNameToInstanceInfoList.findIndex(item => item.instanceName === instanceName);
          }
          if (index === -1) {
            let instanceInfoList = [];
            instanceInfoList.push(instanceInfo);
            let instanceNameToProtoRefInfo = {
              instanceName: instanceName,
              instanceInfoList: instanceInfoList
            }
            this.instanceNameToInstanceInfoList.push(instanceNameToProtoRefInfo);
          } else {
            this.instanceNameToInstanceInfoList[index].instanceInfoList.push(instanceInfo);
            //删除列表中的子节点
            //递归遍历
            if(this.instanceNameToInstanceInfoList[index].instanceInfoList.length === 2) {
              // for (let j = 0; j < this.instanceNameToInstanceInfoList[index].instanceInfoList.length - 1; j++) {
              let ins = this.instanceNameToInstanceInfoList[index].instanceInfoList[0].instance;
              this.currentReNameInstance = null;
              this.traverseAssemblyTreeInstanceId(this.originalAssemblyTree, ins.id);
              if (this.currentReNameInstance) {
                this.deleteChildInstanceElement(this.currentReNameInstance.children);
              }
              // }
            }
            sameFlag = true;
          }
          if(!sameFlag) {
            await this.traverseAssemblyTree(instanceList[i].children);
          }
        } else {
          await this.traverseAssemblyTree(instanceList[i].children);
        }
      }
    },
    countUnderlineChar(str) {
      let count = 0;
      for (let i = 0; i < str.length; i++) {
        if (str[i] === '_') {
          count++;
        }
      }
      return count;
    },
    traverseAssemblyTreeInstanceId(instanceList, instanceId) {
      for(let i = 0; i < instanceList.length; i++) {
        if(instanceId === instanceList[i].id) {
          this.currentReNameInstance = instanceList[i];
        } else {
          this.traverseAssemblyTreeInstanceId(instanceList[i].children, instanceId);
        }
      }
    },
    deleteChildInstanceElement(instanceList) {
      for(let i = 0; i < instanceList.length; i++) {
        let instanceId = instanceList[i].id;
        let name = instanceList[i].name;
        let instanceName = instanceList[i].instanceName;

        //实例名处理
        let index = - 1;
        let index1 = instanceName.indexOf('GBN');
        if (index1 !== -1) {
          let tempInstanceName = instanceName;
          let index2 = tempInstanceName.indexOf('<');
          if (index2 !== -1) {
            tempInstanceName = tempInstanceName.substr(0, index2);
            instanceName = tempInstanceName;
          }
          let currentUnderlineCount = this.countUnderlineChar(instanceName);
          for(let j = 0; j < this.instanceNameToInstanceInfoList.length; j++) {
            let tempInstanceName = this.instanceNameToInstanceInfoList[j].instanceName;
            let tempUnderlineCount = this.countUnderlineChar(tempInstanceName);
            if(tempUnderlineCount === currentUnderlineCount - 1) {
              let pos = instanceName.lastIndexOf('_');
              let currentInstanceName = instanceName.substr(0, pos);
              if(currentInstanceName === tempInstanceName) {
                instanceName = currentInstanceName;
                index = j;
              }
            }
          }
        } else {
          instanceName = name;
        }

        //遍历实例列表
        for(let j = 0; j < this.instanceNameToInstanceInfoList.length; j++) {
          let item = this.instanceNameToInstanceInfoList[j];
          if(instanceName === item.instanceName) {
            for(let k = 0 ; k < item.instanceInfoList.length; k++) {
              let info = item.instanceInfoList[k];
              if (instanceId === info.instance.id) {
                this.instanceNameToInstanceInfoList.splice(j, 1);
              }
            }
          }
        }
        this.deleteChildInstanceElement(instanceList[i].children);
      }
    },
    //检查是否存在同名实例
    checkInstanceNameToProtoRefInfoList() {
      if(!this.instanceNameToInstanceInfoList || this.instanceNameToInstanceInfoList?.length === 0) {
        return;
      }
      for(let i = 0; i < this.instanceNameToInstanceInfoList.length; i++) {
        if(this.instanceNameToInstanceInfoList[i].instanceInfoList.length > 1) {
          let instanceName = this.instanceNameToInstanceInfoList[i].instanceName;
          if(instanceName.indexOf("GBN") !== -1) {
            this.hasSameInstanceName = true;
            break;
            return;
          }
        }
      }
    },
	  //搜索文件夹
    changeSearchParts(newVal, oldVal){
      if(newVal !== oldVal){
        if(newVal !== ''){
          let list = this.folderList.filter(doc=>{
            return doc.name.toLowerCase().indexOf(newVal.toLowerCase()) !== -1
          });

          this.currentFolderList = list;
        } else if(newVal === '') {
          this.currentFolderList = this.folderList;
        }
      }
    },
	  //选择文件夹
    selectDoc(doc, event) {
      if (event.button !== 0) {
        return;
      }
      if(this.selectedDocList.length === 0) {
        doc.isSelected = true;
        this.selectedDocList.push(doc);
        this.editingDocumentFolderCode = doc.id;
        //this.isInit = false;
      } else {
        if (doc === this.selectedDocList[0]) {
          this.selectedDocList.length = 0;
          doc.isSelected = false;
          this.selectedDocList = [];
          this.editingDocumentFolderCode = "";
          //this.isInit = true;
        } else {
          if (this.selectedDocList[0]) {
            this.selectedDocList[0].isSelected = false;
            this.selectedDocList = [];
          }
          doc.isSelected = true;
          this.selectedDocList.push(doc);
          this.editingDocumentFolderCode = doc.id;
          //this.isInit = false;
        }
      }
      //console.log("selectDoc: " + doc.name);
    },
	  //调整界面高度
    handleTotalHeight(value) {
      //console.log('Documents TotalHeight: ' + value);
      let height = value;
      if(height > 200) {
        height = 200;
      }
      this.changePluginContainerHeight(height);
    },
    checkSelectFolder() {
      if(this.selectedDocList.length <= 0) {
        let msg = this.$t('message.ConvertHIToHATool.pleaseSelectFolder');
        convertHIToHACommand.eventBusAlertMsg(msg, 'warning');
        this.isInit = true;
        return false;
      } else {
        return true;
      }
    },
    //导出
    async clickExport() {
      //是否存在同名实例
      this.checkInstanceNameToProtoRefInfoList();
      if(!this.hasSameInstanceName) {
        let msg = this.$t('message.ConvertHIToHATool.notExistSameInstanceName');
        convertHIToHACommand.eventBusAlertMsg(msg, 'warning');
        return;
      }

      //await this.createTemplate();
      this.isInit = true;
      //是否选择导出文件夹
	    // let isSelectFolde = this.checkSelectFolder();
      // if(!isSelectFolde) {
      //   return;
      // }
      await this.createNewFolder();
      await this.createNewRootAssembly();
      await this.createNewAssemblyTree();
      await this.deleteNewRootInstance();
      //await this.createFormNewSubassembly();
      //await this.afterExport();
      await this.reset();
      this.successInfo();
      this.isInit = false;
    },
    //创建模板
    async createTemplate() {
      //装配文档模板
      let assemblyTemplate = await convertHIToHACommand.getTemplate(DocumentType.ASSEMBLY);
      this.currentAssemblyTemplates = assemblyTemplate;
      this.selectAssemblyTemplateId();

      //零件文档模板
      // let partTemplate = await convertHIToHACommand.getTemplate(DocumentType.PART);
      // this.currentAssemblyTemplates = partTemplate;
      // this.selectPartTemplateId();
    },
    //创建新文件夹
    async createNewFolder() {
      if(this.selectedDocList.length === 1) {
        this.editingDocumentFolderCode = this.selectedDocList[0].id;
      } else if(this.selectedDocList.length === 0) {
        // let msg = this.$t('message.ConvertHIToHATool.pleaseSelectFolder');
        // convertHIToHACommand.eventBusAlertMsg(msg, 'warning');
        // this.isInit = true;
        this.editingDocumentFolderCode = this.editingDocument.folderCode
      }
      let folderDoc = await this.createNewFolderDoc(this.folderName);
      if (folderDoc) {
        this.folderCode = folderDoc.id;
        this.lastFolderName = folderDoc.name;
      }
    },
    //创建新项目
    async createNewProject(projectName) {
      let data = {
        projectName: projectName,
        privateOwned: "true",
        folderCode: "0",
        empty: false,
        targetId: this.targetId,
        ownerType: "INDIVIDUAL",
      };
      convertHIToHACommand.createNewProject(data, async res => {
        if (res) {
          console.log("newProjectId:" + res);
          this.newProjectId = res;
        }
      });
    },
    //创建新总装配
    async createNewRootAssembly() {
      //创建新总装配文档
      let rootDoc = await this.createNewAssemblyDoc(this.editingDocumentName);
      if (rootDoc) {
        let instance = await convertHIToHACommand.getInstanceTree();
        if(instance) {
          let part = {
            instanceId: instance[instance.length - 1]?.id,
            name: instance[instance.length - 1]?.name,
            type: instance[instance.length - 1]?.type ? instance[instance.length - 1]?.type : ""
          }
          this.rootAssemblInfo = {
            instance: part,
            doc: rootDoc
          };
        }
      }
    },
    //创建新装配树
    async createNewAssemblyTree1() {
      for(let i = 0; i < this.instanceNameToInstanceInfoList.length; i++) {
        let item = this.instanceNameToInstanceInfoList[i];
        if(item.instanceInfoList.length < 2) {
          continue;
        }
        let tempInstanceName = item.instanceName;
        let index = tempInstanceName.indexOf('<');
        if (index !== -1) {
          tempInstanceName = tempInstanceName.substr(0, index);
        }

        //获创建新装配文档
        let assemblyDoc = await this.createNewAssemblyDoc(tempInstanceName);
        if (assemblyDoc) {
          let instance = await convertHIToHACommand.getInstanceTree();
          if(instance) {
            let newInstanceId = instance[instance.length - 1]?.id;
            let part = {
              instanceId: instance[instance.length - 1]?.id,
              name: instance[instance.length - 1]?.name,
              type: instance[instance.length - 1]?.type ? instance[instance.length - 1]?.type : ""
            }
            this.newInstanceList.push(part);
            let active = await convertHIToHACommand.setTopDownManagerActivate(newInstanceId);
            if(active) {
              for(let j = 0; j < item.instanceInfoList.length; j++) {
                let doc = await convertHIToHACommand.getDocumentById(item.instanceInfoList[j].protoRefInfo.protoRefDocId);
                if (doc) {
                  //在新建的装配文档中插入零件
                  await this.insertPart(doc, assemblyDoc, item.instanceInfoList[j]);
                }
              }
              await convertHIToHACommand.exitEditingComponent();
            }
          }
        }
      }
    },
    async createNewAssemblyTree() {
      for(let i = 0; i < this.instanceNameToInstanceInfoList.length; i++) {
        let item = this.instanceNameToInstanceInfoList[i];
        if(item.instanceInfoList.length === 1 && item.instanceInfoList[0].protoRefInfo.protoRefType === "part") {
          //遍历父级节点,判断父级节点是否创建过，创建过就不再创建，反之
          let result = this.checkParentCreated(item.instanceInfoList[0].instance);
          if(result) {
            continue;
          }
          if (this.rootAssemblInfo.doc) {
            let rootActive = await convertHIToHACommand.setTopDownManagerActivate(this.rootAssemblInfo.instance.instanceId);
            if(rootActive) {
              for(let j = 0; j < item.instanceInfoList.length; j++) {
                let doc = await convertHIToHACommand.getDocumentById(item.instanceInfoList[j].protoRefInfo.protoRefDocId);
                if (doc) {
                  //在新建的装配文档中插入零件
                  await this.insertPart(doc, this.rootAssemblInfo.doc, item.instanceInfoList[j]);
                  this.createdInstanceIdList.push(item.instanceInfoList[j].instance.id);
                }
              }
              await convertHIToHACommand.exitEditingComponent();
            }
          }
        } else if(item.instanceInfoList.length === 1 && item.instanceInfoList[0].protoRefInfo.protoRefType === "assembly") {
          //遍历父级节点,判断父级节点是否创建过，创建过就不再创建，反之
          let result1 = this.checkParentCreated(item.instanceInfoList[0].instance);
          if(result1) {
            continue;
          }
          let ins = item.instanceInfoList[0].instance;
          this.currentReNameInstance = null;
          this.isChildrenReName = false;
          this.traverseAssemblyTreeInstanceId(this.originalAssemblyTree, ins.id);
          console.log('this.currentReNameInstance.name: ' + this.currentReNameInstance.name);
          this.traverseCheckChildrenReName(this.currentReNameInstance.children);
          console.log('this.isChildrenReName: ' + this.isChildrenReName);
          if(this.isChildrenReName) {
            continue;
          }
          if (this.rootAssemblInfo.doc) {
            let rootActive = await convertHIToHACommand.setTopDownManagerActivate(this.rootAssemblInfo.instance.instanceId);
            if(rootActive) {
              for(let j = 0; j < item.instanceInfoList.length; j++) {
                let doc = await convertHIToHACommand.getDocumentById(item.instanceInfoList[j].protoRefInfo.protoRefDocId);
                if (doc) {
                  //在新建的装配文档中插入零件
                  await this.insertPart(doc, this.rootAssemblInfo.doc, item.instanceInfoList[j]);
                  this.createdInstanceIdList.push(item.instanceInfoList[j].instance.id);
                }
              }
              await convertHIToHACommand.exitEditingComponent();
            }
          }
        } else if(item.instanceInfoList.length >= 2) {
          //遍历父级节点,判断父级节点是否创建过，创建过就不再创建，反之
          let isCreated = false;
          let noCreatedList = [];
          for(let insIndex = 0; insIndex < item.instanceInfoList.length; insIndex++) {
            let result = this.checkParentCreated(item.instanceInfoList[insIndex].instance);
            if(!result) {
              noCreatedList.push(item.instanceInfoList[insIndex]);
            }
          }
          if(noCreatedList.length === 0) {
            continue;
          }
          let tempInstanceName = item.instanceName;
          let index = tempInstanceName.indexOf('<');
          if (index !== -1) {
            tempInstanceName = tempInstanceName.substr(0, index);
          }
          let reAssemblyName = await this.checkReAssemblyDocName(tempInstanceName);
          if (reAssemblyName) {
            let insName = item.instanceName;
            let symbolIndex1 = insName.indexOf('<');
            let numberStr = '1';
            if (symbolIndex1 !== -1) {
              let tempName = insName.substr(symbolIndex1 + 1);
              let symbolIndex2 = tempName.indexOf('>');
              if (symbolIndex2 !== -1) {
                numberStr = tempName.substr(0, symbolIndex2);
                let number = parseInt(numberStr);
                if (number > 1) {
                  number--;
                  numberStr = number.toString();
                }
              }
            }
            tempInstanceName = tempInstanceName + '(' + numberStr + ')';
          }

          if (this.rootAssemblInfo.doc) {
            let rootActive = await convertHIToHACommand.setTopDownManagerActivate(this.rootAssemblInfo.instance.instanceId);
            if (rootActive) {
              //创建新装配文档
              let assemblyDoc = await this.createNewAssemblyDoc(tempInstanceName);
              await convertHIToHACommand.exitEditingComponent();
              if (assemblyDoc) {
                let instance = await convertHIToHACommand.getInstanceTree();
                if (instance) {
                  let instanceIndex = instance.length - 1;
                  let childrenIndex = instance[instanceIndex]?.children?.length - 1;
                  let newInstanceId = instance[instanceIndex]?.children[childrenIndex].id;
                  let part = {
                    instanceId: instance[instance.length - 1]?.id,
                    name: instance[instance.length - 1]?.name,
                    type: instance[instance.length - 1]?.type ? instance[instance.length - 1]?.type : ""
                  }
                  this.newInstanceList.push(part);
                  let active = await convertHIToHACommand.setTopDownManagerActivate(newInstanceId);
                  if (active) {
                    for (let j = 0; j < noCreatedList.length; j++) {
                      let doc = await convertHIToHACommand.getDocumentById(noCreatedList[j].protoRefInfo.protoRefDocId);
                      if (doc) {
                        //在新建的装配文档中插入零件
                        await this.insertPart(doc, assemblyDoc, noCreatedList[j]);
                        this.createdInstanceIdList.push(noCreatedList[j].instance.id);
                      }
                    }
                    await convertHIToHACommand.exitEditingComponent();
                  }
                }
              }
            }
          }
        }
      }
    },
    //检查父级节点是否已经插入过
    checkParentCreated(instance) {
      let result = this.traverseParents(instance);
      return result;
    },
    //遍历父节点
    traverseParents(instance) {
      // if(instance.parentId && instance.parentName) {
      //   let index = this.instanceNameToInstanceInfoList.findIndex(item => item.instanceName === instance.parentName);
      //   if(index !== -1) {
      //     let length = this.instanceNameToInstanceInfoList[index].instanceInfoList.length;
      //     if(length === 1) {
      //       let result = this.traverseParents(this.instanceNameToInstanceInfoList[index].instanceInfoList[0].instance);
      //       if(!result) {
      //         return false;
      //       }
      //     } else if(length > 1){ //不插入此实例
      //       return false;
      //     }
      //   }
      // } else { //插入此实例
      //   return true;
      // }
      if(instance.parentId && instance.parentName) {
        let index = this.instanceNameToInstanceInfoList.findIndex(item => item.instanceName === instance.parentName);
        if(index !== -1) {
          let createdIndex = this.createdInstanceIdList.findIndex(id => id === instance.parentId)
          if(createdIndex === -1) {
            return (this.traverseParents(this.instanceNameToInstanceInfoList[index].instanceInfoList[0].instance));
          } else { //不插入此实例
            return true;
          }
        }
      } else { //插入此实例
        return false;
      }
    },
    //遍历子节点
    traverseCheckChildrenReName(instanceList) {
      for(let i = 0; i < instanceList.length; i++) {
        let name = instanceList[i].name;
        let instanceName = instanceList[i].instanceName;

        //实例名处理
        let index = - 1;
        let index1 = instanceName.indexOf('GBN');
        if (index1 !== -1) {
          let tempInstanceName = instanceName;
          let index2 = tempInstanceName.indexOf('<');
          if (index2 !== -1) {
            tempInstanceName = tempInstanceName.substr(0, index2);
            instanceName = tempInstanceName;
          }
          let currentUnderlineCount = this.countUnderlineChar(instanceName);
          for(let j = 0; j < this.instanceNameToInstanceInfoList.length; j++) {
            let tempInstanceName = this.instanceNameToInstanceInfoList[j].instanceName;
            let tempUnderlineCount = this.countUnderlineChar(tempInstanceName);
            if(tempUnderlineCount === currentUnderlineCount - 1) {
              let pos = instanceName.lastIndexOf('_');
              let currentInstanceName = instanceName.substr(0, pos);
              if(currentInstanceName === tempInstanceName) {
                instanceName = currentInstanceName;
                index = j;
              }
            }
          }
        } else {
          instanceName = name;
        }

	      //查找同名实例
        index = this.instanceNameToInstanceInfoList.findIndex(item => item.instanceName === instanceName);
        if(index !== - 1) {
          let item = this.instanceNameToInstanceInfoList[index];
          if(item.instanceInfoList.length > 1) {
            this.isChildrenReName = true;
            return;
          } else {
            this.traverseCheckChildrenReName(instanceList[i].children);
          }
        } else {
          this.traverseCheckChildrenReName(instanceList[i].children);
        }
      }
    },
    //创建新子装配
    async createFormNewSubassembly() {
      if(!this.newInstanceList || this.newInstanceList?.length === 0) {
        return;
      }
      let params = {
        moveParts: this.newInstanceList,
        docName: this.editingDocumentName,
        folderCode: this.folderCode
      }
      let res = await convertHIToHACommand.createFormNewSubassembly(params);
      if(res) {
        await this.deleteNewInstances();
      }
    },
    //删除新建实例
    async deleteNewInstances() {
      let instance = await convertHIToHACommand.getInstanceTree();
      if(instance) {
        let part = {
          instanceId: instance[instance.length - 1]?.id,
          name: instance[instance.length - 1]?.name,
          type: instance[instance.length - 1]?.type ? instance[instance.length - 1]?.type : ""
        }
        this.newInstanceList.push(part);
      }
      let ins = {
        id: this.newInstanceList[this.newInstanceList.length - 1].instanceId
      }
      await convertHIToHACommand.deleteInstanceByInstanceId({instanceIdList: [ins]});
    },
    //创建新文件夹文档
    async createNewFolderDoc(docName) {
      this.currentDocType = DocumentType.FOLDER;
      let projectId = this.newProjectId;
      let currentDocType = this.currentDocType;
      let folderCode = this.editingDocumentFolderCode;

      let config = {
        projectId: projectId,
        docName: docName,
        docType: currentDocType,
        folderCode: folderCode,
      }
      let folderDoc = await convertHIToHACommand.createNewDoc(config);
      return folderDoc;
    },
    //创建新装配文档
    async createNewAssemblyDoc(docName){
      this.currentDocType = DocumentType.ASSEMBLY;
      let projectId = this.newProjectId;
      let currentDocType = this.currentDocType;
      let folderCode = this.folderCode;
      let docInfo = null;
      let relatedModelVersionId = docInfo ? docInfo?.activeVersionId : "";
      let relatedModelDocId = docInfo ? docInfo?.id : "";

      let templateId = this.assemblyTemplateInfo.templateId;

      let config = {
        projectId: projectId,
        docName: docName,
        docType: currentDocType,
        folderCode: folderCode,
        templateId: templateId,
        relatedModelVersionId: relatedModelVersionId,
        relatedModelDocId: relatedModelDocId
      }
      let assemblyDoc = await convertHIToHACommand.createNewDoc(config);
      return assemblyDoc;
    },
    //创建新零件文档
    async createNewPartDoc(docName){
      this.currentDocType = DocumentType.PART;
      let projectId = this.newProjectId;
      let currentDocType = this.currentDocType;
      let docInfo = null;
      let relatedModelVersionId = docInfo ? docInfo?.activeVersionId : "";
      let relatedModelDocId = docInfo ? docInfo?.id : "";

      let templateId = this.partTemplateInfo.templateId;

      let config = {
        projectId: projectId,
        docName: "Part01",
        docType: currentDocType,
        folderCode: '0',
        templateId: templateId,
        relatedModelVersionId: relatedModelVersionId,
        relatedModelDocId: relatedModelDocId
      }
      let partDoc = await convertHIToHACommand.createNewDoc(config);
      return partDoc;
    },
    //插入零件
    async insertPart(doc, assemblyDoc, instanceInfo) {
      let curPreviewDoc = doc;
      let insertProjectId = curPreviewDoc?.projectId;
      let curPreviewDocId = curPreviewDoc?.id;
      let insertVersionId = instanceInfo.protoRefInfo.protoRefVersionId;
      let insertVersionVirtual = true;
      let instanceName = curPreviewDoc?.name;

      const boxCenter = 1;// 是否使用原点插入 0 表示原点插入
      //const insertPosition = new Vector3(0, 0, 0);
      const insertPosition = instanceInfo.instance.position;// 原点插入将插入点设置为[0,0,0]
      const trsType = 1;// 是否使用矩阵插入
      //const insertMatrix = '';
      const insertMatrix = instanceInfo.instance.matrixWorld;// 原点插入将矩阵设置为单位矩阵
      const trsfMat = {trsfMat: ''};// 需要将矩阵前端后端传递格式一致; ThreeJS.Matrix4 转换成 12Numbers
      const isInsertVirtual =false;

      let params = {
        instanceName: instanceName,
        insertProjectId: insertProjectId,
        insertVersionId: insertVersionId,
        insertVersionVirtual: insertVersionVirtual, //true
        curPreviewDocId: curPreviewDocId, //insertDocumentId
        insertPosition: insertPosition,
        boxCenter: boxCenter,
        trsType: trsType,
        insertMatrix: insertMatrix,
        trsfMat: trsfMat,
        isInsertVirtual: isInsertVirtual,
        editingDocumentData: {
          projectId: assemblyDoc.projectId,
          documentId: assemblyDoc.id,
          versionId: assemblyDoc.activeVersionId
        },
        enableOriginPointInsert: true //1表示原点插入
      }
      let part = await convertHIToHACommand.insertPart(params);
    },
    //装配模板号
    selectAssemblyTemplateId() {
      if(!this.currentAssemblyTemplates){
        return;
      }
      this.assemblyTemplateInfo.templateId = this.currentAssemblyTemplates.templateId;
      this.assemblyTemplateInfo.templateName = this.currentAssemblyTemplates.templateName;
      this.assemblyTemplateInfo.templateType = this.currentAssemblyTemplates.templateType;
      this.assemblyTemplateInfo.orderNumber = this.currentAssemblyTemplates.orderNumber;
      this.assemblyTemplateInfo.defaultTemplate = this.currentAssemblyTemplates.defaultTemplate;
      this.assemblyTemplateInfo.attrManifestTemplateId = this.currentAssemblyTemplates.attrManifestTemplateId;
    },
    //零件模板号
    selectPartTemplateId() {
      if(!this.currentPartTemplates){
        return;
      }
      this.partTemplateInfo.templateId = this.currentPartTemplates.templateId;
      this.partTemplateInfo.templateName = this.currentPartTemplates.templateName;
      this.partTemplateInfo.templateType = this.currentPartTemplates.templateType;
      this.partTemplateInfo.orderNumber = this.currentPartTemplates.orderNumber;
      this.partTemplateInfo.defaultTemplate = this.currentPartTemplates.defaultTemplate;
      this.partTemplateInfo.attrManifestTemplateId = this.currentPartTemplates.attrManifestTemplateId;
    },
    //改变文件夹名称
    async checkReAssemblyDocName(docName) {
      let params = {
        docName: docName,
        docType: DocumentType.ASSEMBLY,
        folderCode: this.folderCode
      }
      //检查同名装配文档
      let res = await convertHIToHACommand.checkRepeatDocumentName(params);
      if(res) {
        return true;
      } else {
        return false;
      }
    },
    //参数重置
    async reset() {
      this.folderName = await convertHIToHACommand.getDefaultDocumentName(DocumentType.FOLDER);
      this.newInstanceList = [];
    },
    async deleteNewRootInstance() {
      await convertHIToHACommand.saveDocument();
      let id = this.rootAssemblInfo.instance.instanceId;
      let ins = {
        id: id
      }
      await convertHIToHACommand.deleteInstanceByInstanceId({instanceIdList: [ins]});
      await convertHIToHACommand.saveDocument();
    },
    //导出完成后的处理
    async afterExport() {
      await convertHIToHACommand.saveDocument();
      this.newAssemblyTree = await convertHIToHACommand.getInstanceTree();
      if (this.newAssemblyTree !== this.originalAssemblyTree) {
        for (const item of this.newAssemblyTree) {
          let instance = item;
          let index = this.originalAssemblyTree.findIndex(ins => ins.id === instance.id);
          if (index === -1) {
            let ins = {
              id: instance.id
            }
            await convertHIToHACommand.deleteInstanceByInstanceId({instanceIdList: [ins]});
          }
        }
      }
      await convertHIToHACommand.saveDocument();
    },
    successInfo() {
      let msg = this.$t('message.ConvertHIToHATool.successInfo');
      let parentDoc = null;
      if(this.selectedDocList.length === 1) {
        parentDoc = this.selectedDocList[0];
        this.path = parentDoc.name;
        this.traceParentFolderPath(parentDoc);
        this.path = this.path + "//" + this.lastFolderName + "//" + this.editingDocumentName;
        msg = msg + this.path;
      } else if(this.selectedDocList.length === 0) {
        parentDoc = this.editingDocument;
        this.path = "";
        this.traceParentFolderPath(parentDoc);
        this.path = this.path + "//" + this.lastFolderName+ "//" + this.editingDocumentName;
        msg = msg + this.path;
      }
      console.log('msg: ' + msg);
      convertHIToHACommand.eventBusAlertMsg(msg, 'success');
    },
    traceParentFolderPath(doc) {
      if(doc.parent) {
        let parentDoc = doc.parent;
        let parentName = parentDoc?.name
	      let symbol = "//";
        if(this.path === "") {
          symbol = "";
        }
        this.path = parentName + symbol + this.path;
        this.traceParentFolderPath(parentDoc);
      } else {
        return this.path;
      }
    },
    async close() {
      await this.afterExport();
      convertHIToHACommand.closeActiveCmd();
    },
	  checkFolderCodeIsRootCode() {
      let list;
      //通过 electricalParam 识别是否为检索出来的电气部件模型, 电气部件模型不需要比对文件夹Code, 直接陈列
      if (!this.folderList[0]?.electricalParam) {
        list = [...this.folderList.filter(doc => doc.folderCode === this.rootCode)];
      } else {
        list = [...this.folderList];
      }
      let length = list.length;
      let height = 0;
      if(length === 0) {
        height = 0;
      } else  {
        height = 5 * 45;
      }
      return height;
	  },
    changePluginContainerHeight(height) {
      convertHIToHACommand.changePluginContainerHeight({
	      minWidth: this.$el.clientWidth, maxHeight: height + 142})
    },
  },

  beforeDestroy() {

  },

  computed: {

  },

  destroyed() {
  }
}

</script>

<style scoped>
.wrap {
    font-size: 12px;
}

.el-upload__text {
    color: #409eff;
    font-size: 15px;
}

el-upload__text:after {
    color: #409eff;
    font-size: 15px;
}

.upload-icon {
    font-size: 2em;
    margin: 0;
    color: #C0C4CC;
}

>>> .el-upload-list {
    max-height: 30vh;
    overflow-y: auto;
}





select{
    outline: none;
    border: none;
    border-bottom: 1px solid lightgray;
}

.op-list-container .op-item select, .op-item input{
    width: 150px;
}

.op-dialog-part-disabled {
    opacity: .5;
}

.op-fork-button {
    height: 30px;
    width: 30px;
    margin: 0 5px;
    border-radius: 3px;
    outline: none;
    border: none;
    background-color: var(--bg-color9);
    box-shadow: 0 0 1px 1px var(--bg-color2);
    transition-duration: 0.4s;
    font-size: 19px;
}

.op-fork-button:hover {
    background-color: var(--bg-color2);
}

.op-fork-button[disabled]:hover {
    cursor: not-allowed;
    background-color: var(--bg-color9);
}

.op-fork-button:active {
    background-color: var(--bg-color2);
    box-shadow: 1px 1px var(--bg-color9);
    transform: translateY(1px);
}

.part-version {
    position: relative;
    max-height: 400px;
    min-height: 200px;
    overflow: auto;
}

.version-canvas {
    position: absolute;
    left: 0;
    pointer-events: none;
}

.op-scroll-container {
    max-height: 200px;
}

.op-back-button {
    display: flex;
    align-items: center;
    height: 26px;
}

.op-content-title-version {
    max-width: 85%;
}

.op-content-alt {
    color: var(--text-color3);
    padding: 10px 5px;
}

.version-nodes {
    margin: 1px;
}

/*>>> input {*/
/*    border: none !important;*/
/*    background-color: var(--bg-color10) !important;*/
/*    color: var(--text-color1) !important;*/
/*}*/

.list-loading {
    text-align: center;
    min-height: 30px;
}
.text-danger {
    font-size: 13px;
    color: red;
}
.search-top {
    margin-top: 5px;
}

</style>